package com.csthink.mr.inputformat;

import com.csthink.mr.wordcount.WordCountDriver;
import com.csthink.mr.wordcount.WordCountMapper;
import com.csthink.mr.wordcount.WordCountReducer;
import com.csthink.utils.FileUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

import static org.apache.hadoop.mapreduce.lib.input.KeyValueLineRecordReader.KEY_VALUE_SEPARATOR;

/**
 * 演示 KeyValueTextInputFormatApp 的使用，可以使用分隔符分割每行的数据进行处理
 *
 * @author <a href="mailto:csthink@icloud.com">Mars</a>
 * @since 2024-04-15 10:10
 */
public class KeyValueTextInputFormatApp {

    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        String input = "data/kv.txt";
        String output = "out";

        Configuration conf = new Configuration();
        conf.set(KEY_VALUE_SEPARATOR, ",");
        Job job = Job.getInstance(conf);

        FileUtils.deleteIfExists(conf, output);

        job.setJarByClass(KeyValueTextInputFormatApp.class);

        job.setMapperClass(MyMapper.class);
        job.setReducerClass(MyReducer.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        job.setInputFormatClass(KeyValueTextInputFormat.class);
        FileInputFormat.setInputPaths(job, new Path(input));
        FileOutputFormat.setOutputPath(job, new Path(output));

        boolean result = job.waitForCompletion(true);
        System.exit(result ? 0 : 1);

    }

    public static class MyMapper extends Mapper<Text, Text, Text, IntWritable> {

        public static final IntWritable ONE = new IntWritable(1);

        @Override
        protected void map(Text k1, Text v1, Context context) throws IOException, InterruptedException {
           context.write(k1, ONE);
        }
    }

    public static class MyReducer extends Reducer<Text, IntWritable, Text, IntWritable> {

        @Override
        protected void reduce(Text k2, Iterable<IntWritable> v2s, Context context) throws IOException, InterruptedException {
            int sum = 0;
            for (IntWritable v2 : v2s) {
                sum += v2.get();
            }

            context.write(k2, new IntWritable(sum));
        }
    }
}
